<template>

    <el-dialog :title="id == null ? $t('page-form.form.add') : $t('page-form.form.edit')" :visible.sync="visible" :loading="true" :close-on-click-modal="false" width="800px">

      <el-form ref="main-form" status-icon :model="mainQuery" :rules="rules" label-width="100px" label-position="right" :inline="false">

        <el-form-item :label="$t('page-sys-user.d2-crud.column-strRole')" size="mini" prop="roleId">
          <el-select v-model="mainQuery.roleId" :placeholder="$t('page.form.pleaseselectstatus')" clearable :disabled="loading">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <template v-if="!!data">
          <el-form-item :label="$t('page-sys-user.d2-crud.column-username')" size="mini" prop="">
            <span>{{mainQuery.username}}</span>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="$t('page-sys-user.d2-crud.column-username')" size="mini" prop="username">
            <el-input placeholder="" v-model="mainQuery.username" @keyup.enter.native="submit" :readonly="!!id" :disabled="loading" clearable></el-input>
          </el-form-item>
        </template>

        <template v-if="resetPassword || id == null">
          <el-form-item :label="$t('page-register.form.password')" size="mini" prop="password">
            <el-input placeholder="" type="password" v-model="mainQuery.password" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
          <el-form-item :label="$t('page-register.form.password-next')" size="mini" prop="password_confirmation">
            <el-input placeholder="" type="password" v-model="mainQuery.password_confirmation" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
        </template>

        <el-form-item size="mini" prop="" v-if="id != null">
          <el-button v-if="!resetPassword" @click="handleResetPassword" type="warning" plain :disabled="loading">{{ $t('page.form.resetpasswords') }}</el-button>
          <el-button v-else @click="handleResetPassword" :disabled="loading">{{ $t('page.form.cancel') }}</el-button>

        </el-form-item> 


        <el-form-item :label="$t('page-sys-user.d2-crud.column-nick')" size="mini" prop="nick">
          <el-input placeholder="" v-model="mainQuery.nick" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item :label="$t('page-sys-user.d2-crud.column-realName')" size="mini" prop="realName">
          <el-input placeholder="" v-model="mainQuery.realName" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item :label="$t('page-register.form.phone')" size="mini" prop="mobile">
          <el-input placeholder="" v-model="mainQuery.mobile" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item label="Email" size="mini" prop="email">
          <el-input placeholder="" v-model="mainQuery.email" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>

      

        <el-form-item :label="$t('page-sys-user.d2-crud.column-strStatus')" size="mini" prop="status">

          <el-radio-group v-model="mainQuery.status">
            <el-radio v-for="item in statusOptions" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">

        <el-popover
          v-if="false"
          placement="top"
          width="160"
          v-model="popDeleteVisible">
          <p>{{ $t('page.form.tips65') }}</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="default" @click="popDeleteVisible = false">{{ $t('page.form.submit') }}</el-button>
            <el-button type="danger" size="mini" @click="submitDel">{{ $t('page.form.confirm') }}</el-button>
          </div>
          <el-button type="danger" slot="reference" size="small" style="float: left;" :loading="loading">{{ $t('page.form.delete') }}</el-button>
        </el-popover>

        <span style="float: left;">
          <el-button @click="handleResetGoogleAuthencator" size="small" type="warning" plain :disabled="loading">{{ $t('page.form.reset-google-authenticator') }}</el-button>
        </span>

        <el-button @click="close" size="mini">{{ $t('page.form.cancel') }}</el-button>
        <el-button @click="submit" size="mini" type="primary" :loading="loading">{{ $t('page.form.submit') }}</el-button>
      </div>
    </el-dialog>

</template>

<script>

import { mapState, mapActions } from 'vuex'
import ApiMain from '@/api/merchant.member';

export default {
  mixins: [
  ],
  props: [
    'statusOptions',
    'roleOptions',
  ],
  data () {
    return {

      visible         : false,
      popDeleteVisible: false,
      loading         : false,

      mainQueryRaw: null,
      mainQuery   : {
        username       : '',
        password       : '',
        password_confirmation: '',
        nick           : '',
        realName       : '',
        email          : '',
        mobile         : '',
        roleId         : '',
        status         : 0 ,
        // terIdList      : [],
      },

      rules: {
        username: [
          { required: true, message: this.$t('page.form.tips66'), trigger: 'blur' },
          { min: 4, max: 99, message: this.$t('page.form.tips67'), trigger: 'blur' }
        ],
        nick: [
          { required: true, message: this.$t('page.form.tips68'), trigger: 'blur' },
        ],
        realName: [
          { required: true, message: this.$t('page.form.tips69'), trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: this.$t('page.form.tips70'), trigger: 'blur' },
        ],
        email: [
          { required: true, message: this.$t('page.form.tips71'), trigger: 'blur' },
        ],
        roleId: [
          { required: true, message: this.$t('page.form.tips72'), trigger: 'blur' },
        ],
        status: [
          { required: true, message: this.$t('page.form.tips73'), trigger: 'blur' },
        ],

        password: [
          { required: true, message: this.$t('page.form.tips74'), trigger: 'blur' },
        ],

        password_confirmation: [
          { required: true, message: this.$t('page.form.tips74'), trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value !== this.mainQuery.password) {
                callback(new Error(this.$t('page.form.tips75')));
              }
              else {
                callback();
              }
            }, 
            trigger: 'blur' 
          },
        ],
      },

      id  : null,
      data: null,
      resetPassword: false,
    }
  },
  computed: {
    ...mapState('d2admin/user', {
      user: 'info',
    })
  },
  mounted () {
    this.mainQueryRaw = Object.copy(this.mainQuery);
  },

  methods: {

    show (id = null) {

      this.reset();

      if (id) {
        this.id = id;
        this.fetchData();
      }

      this.visible = true;
    },

    close () {
      this.visible = false;
      this.$emit('dialog-close');
    },

    reset () {

      this.mainQuery = Object.copy(this.mainQueryRaw);
      this.$refs['main-form'] && this.$refs['main-form'].resetFields();

      this.id   = null;
      this.data = null;
      this.resetPassword = false;
    },

    handleResetPassword () {
      this.resetPassword = ! this.resetPassword;
    },

    async handleResetGoogleAuthencator () {
      try {
        var re = await ApiMain.resetGoogleAuthSecret({id: this.id});
        this.$alert(this.$t('page.form.new-google-authenticator-is') + re, {
          title: this.$t('page.form.operatesuccessfully'),
        });
      } catch (err) {}
    },

    async fetchData () {

      this.loading = true;

      try {
        var re = await ApiMain.info({id: this.id});
        this.data = re;
      } catch (err) {
        this.data = null;
      }
      

      this.renderData();

      this.loading = false;
    },

    renderData () {

      this.mainQuery.username  = this.data.username;
      this.mainQuery.realName  = this.data.realName;
      this.mainQuery.nick      = this.data.nick;
      this.mainQuery.email     = this.data.email;
      this.mainQuery.mobile    = this.data.mobile;
      this.mainQuery.roleId    = this.data.roleId;
      this.mainQuery.mchId     = this.data.mchIdList;
      this.mainQuery.status    = this.data.status;
      // this.mainQuery.terIdList = this.data.terList.map(item => item.terId);

    },

    verifyForm () {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit () {

      if (! this.verifyForm()) return false;

      this.loading = true;

      try {
        this.id ? await this.submitSet() : await this.submitAdd();
      } catch (err) {}

      this.loading = false;
    },

    async submitAdd () {
      await ApiMain.add(this.mainQuery);
      this.$message({message: this.$t('page.form.successfullyadded'), type: 'success'});
      this.close();
    },

    async submitSet () {

        var req = Object.copy(this.mainQuery);

        req.id = this.id;

        if (! this.resetPassword) {
          delete req.password;
          delete req.password_confirmation;
        }

        await ApiMain.set(req);
        this.$message({message: this.$t('page.form.modifysuccessfully'), type: 'success'});
        this.close();
    },


  }
}
</script>

<style>

</style>
